/**
 * @description  : 钉钉平台api适配
 * @descriptionDetail : 钉钉平台api适配
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 19:31:34
 */
import {
  pathToBase64,
} from 'image-tools';
import { getData, } from 'exif-js';
import {
	isDD,
} from "../common/util";

import * as EXIF from 'exif-js';
let DingDing = {
	/**
	 * 是否显示顶部的自定义导航栏  并不当做顶部导航栏是否显示，只是用作代码中的配套
	 * @returns
	 */
	isHideNav: () => {
		return isDD();
	},
  /**
	 * 钉钉toast弹窗
	 */
  toast: (str) => {
    sinoware.device.notification.toast({
      text: str, // 提示信息
      onSuccess: function(result) {},
      onFail: function(err) {},
    });
  },
  /**
	 * 钉钉提示
	 * @param {*} msg     提示信息
	 * @param {*} title   标题(可选)
	 */
  alert: (msg, title, success) => {
    sinoware.device.notification.alert({
      message: msg,
      title: title || "提示",
      buttonName: "确定",
      onSuccess: function() {
        // onSuccess将在点击button之后回调
        /* 回调*/
        success();
      },
      onFail: function(err) {},
    });
  },
  /**
	 * 钉钉确认框
	 */
  confirm: (msg, title, btns, success) => {
    sinoware.device.notification.confirm({
      message: msg,
      title: title,
      buttonLabels: btns,
      onSuccess: function(result) {
        success(result.buttonIndex);
      },
      onFail: function(err) {},
    });
  },
  // 开始录音
  startRecord: () => {
    return new Promise(function(resolve, reject) {
      sinoware.device.audio.startRecord({
        maxDuration: 300, // 支持最长为300秒（包括）的音频录制，默认60秒(包括)。
        onSuccess: () => resolve(),
        onFail: err => reject(err),
      });
    });
  },
  // 停止录音
  stopRecord: () => {
    return new Promise(function(resolve, reject) {
      sinoware.device.audio.stopRecord({
        // res.mediaId; // 返回音频的MediaID，可用于本地播放和音频下载
        // res.duration; // 返回音频的时长，单位：秒
        onSuccess: res => resolve(res),
        onFail: err => reject(err),
      });
    });
  },
  // 监听录音自动停止
  onRecordEnd: () => {
    return new Promise(function(resolve, reject) {
      sinoware.device.audio.onRecordEnd({
        // res.mediaId; // 停止播放音频MediaID
        // res.duration; // 返回音频的时长，单位：秒
        onSuccess: res => resolve(res),
        onFail: err => reject(err),
      });
    });
  },
  // 下载音频
  downlaod: (mediaId) => {
    return new Promise(function(resolve, reject) {
      sinoware.device.audio.download({
        mediaId: mediaId,
        onSuccess: res => resolve(res.localAudioId),
        onFail: err => reject(err),
      });
    });
  },
  // 播放语音
  play: (localAudioId) => {
    return new Promise(function(resolve, reject) {
      sinoware.device.audio.play({
        localAudioId: localAudioId,
        onSuccess: result => resolve(result),
        onFail: err => reject(err),
      });
    });
  },
  // 图片预览
  previewImage: (urls, current) => {
    return new Promise(function(resolve, reject) {
      // #ifdef H5-DINGDING
      sinoware.biz.util.previewImage({
        urls: urls, // 图片地址列表
        current: current, // 当前显示的图片链接
        onSuccess: result => resolve(result),
        onFail: err => reject(err),
      });
      // #endif
      // #ifndef H5-DINGDING
      uni.previewImage({
        urls: urls,
        current: current,
        success: function(data) {
          resolve(true);
        },
        fail: function(err) {
          console.log(err + "===" + JSON.stringify(err));
          reject(false);
        },
      })
      // #endif
    });
  },
  // 设置标题
  setTitle: (title) => {
    sinoware.biz.navigation.setTitle({
      title: title, // 控制标题文本，空字符串表示显示默认文本
      onSuccess: result => console.log(result),
      onFail: err => console.error(err),
    });
  },
  // 设置右侧单个按钮
  setRight: (text, cb, control, isShow) => {
    sinoware.biz.navigation.setRight({
      show: typeof isShow === 'undefined' ? true : isShow, // 控制按钮显示， true 显示， false 隐藏， 默认true
      control: typeof control === 'undefined' ? true :
        control, // 是否控制点击事件，true 控制，false 不控制， 默认false
      text: text, // 控制显示文本，空字符串表示显示默认文本
      onSuccess: result => cb && cb(result),
      onFail: err => console.error(err),
    });
  },
  /**
	 * 设置导航栏右侧多个按钮(针对不同的点击处理不同的内容)
	 * 苹果手机对此接口的格式要求比较严格，不能出现多余的符号！！！
	 * @param {*} items '[{"id": "1", "text": "刷新"},{"id": "2", "text": "更多"}]'
	 * @param {*} cb 点击后的回调函数    
	 * @param {*} backgroundColor 
	 * @param {*} textColor 
	 * @returns 
	 */
  setMenu: (items, cb, backgroundColor, textColor) => {
    sinoware.biz.navigation.setMenu({
      backgroundColor: backgroundColor || "#ADD8E6",
      textColor: textColor || "#ADD8E611",
      items: items,
      onSuccess: res => {
        cb && cb(res);
      },
      onFail: err => console.error(err),
    });
  },
  /**
	 * 扫码
	 * @param {*} type type 为 all、qrCode二维码、barCode条形码，默认是all。
	 * @returns  { 'text': String}
	 */
  scan: (type) => {
    return new Promise((resolve, reject) => {
      sinoware.biz.util.scan({
        type: type || "all",
        onSuccess: res => resolve(res.text),
        onFail: err => reject(err),
      });
    });
  },
  /**
	 * 二维码扫码
	 * @returns 
	 */
  qrCode: () => {
    return new Promise((resolve, reject) => {
      sinoware.biz.util.scan({
        type: "qrCode",
        onSuccess: res => resolve(res.text),
        onFail: err => reject(err),
      });
    });
  },
  /**
	 * 分享
	 * @returns 
	 */
  shareContent(type, title, url, content) {
    if(content){
      sinoware.biz.util.share({
        type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
        content: content,
        title: title,
        onSuccess: function() {},
        onFail: function() {},
      });
    }else{
      sinoware.biz.util.share({
        type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
        url: url,
        title: title,
        onSuccess: function() {},
        onFail: function() {},
      });
    }
  },
  /**
	 * 条形码扫码
	 * @returns 
	 */
  barCode: () => {
    return new Promise((resolve, reject) => {
      sinoware.biz.util.scan({
        type: "barCode",
        onSuccess: res => resolve(res.text),
        onFail: err => reject(err),
      });
    });
  },
  /**
	 * 拨打电话
	 * @param {*} phoneNum 
	 */
  phone(phoneNum) {
    sinoware.biz.telephone.showCallMenu({
      phoneNumber: phoneNum, // 期望拨打的电话号码
      code: '+86', // 国家代号，中国是+86
      showDingCall: true, // 是否显示钉钉电话
      onSuccess: function() {},
      onFail: function(e) { console.log(e, JSON.stringify(e)) },
    });
  },
  /**
	 * 定位
	 * @returns 
	 */
  geolocation() {
    return new Promise((resolve, reject) => {
      sinoware.device.geolocation.get({
        targetAccuracy: 200,
        coordinate: 1,
        withReGeocode: true,
        useCache: false, // 默认是true，如果需要频繁获取地理位置，请设置false
        onSuccess: function(result) {
          resolve(result);
        },
        onFail: err => reject(err),
      });
    });
  },
  /**
	 * NFC读取
	 * @returns 
	 */
  nfcReader() {
    return new Promise((resolve, reject) => {
      alert('开启识别NFC, 点击确定后, 用手机靠近NFC设备');
      sinoware.device.nfc.nfcRead({
        onSuccess: function(data) {
          resolve(data);
        },
        onFail: function(err) {
          if ((err["tagId"])) {
            let cardId = err["tagId"].replace(/:/g, '').toUpperCase();
            resolve(cardId);
          } else {
            reject(err['errorMessage']);
          }
        },
      });
    });
  },

  /**
	 * 打开指定位置
	 * @param {*} lat     纬度
	 * @param {*} long    经度
	 * @param {*} title   地址/POI名称
	 */
  navigateMap(lat, long, title) {
    sinoware.biz.map.view({
      latitude: lat,
      longitude: long,
      title: title,
    });
  },
  /**
   * 复制到剪切板
   */
  clipboardData(text, callback){
    sinoware.biz.clipboardData.setData({
      text: text,   
      onSuccess : function(result) { callback(true) },
      onFail : function() { callback(false) },
    });
  },
  /**
   * 打开指定聊天页面
   * @param {Object} userId
   */
  openSingleChat(userId, callback){
    sinoware.biz.chat.openSingleChat({
      corpId: 'dingcc3c8a50fc75c24dffe93478753d9884', // 企业id,必须是用户所属的企业的corpid
      userId:userId, // 用户的uerid
      onSuccess : function() { callback(true) },
      onFail : function() { callback(false) },
    })
  },
  /**
	 * 地图选点获取位置
	 */
  getLocationByMap(lat, lng, scope = 500) {
    return new Promise((resolve, reject) => {
      let obj = {};
      if (lat != null && lat != '' && lat != undefined) {
        obj.latitude = lat; // 纬度，非必须
        obj.longitude = lng; // 经度，非必须
      }
      obj.scope = scope;
      obj.onSuccess = function(result) {
        resolve([result.latitude, result.longitude,]);
      };
      obj.onFail = function(err) {
        reject(err);
      };
      sinoware.biz.map.locate(obj);
    });
  },
  
  /**
	 * 地图选点获取位置 带search
	 */
  getLocationInMapBySearch(lat, lng, scope = 500) {
    return new Promise((resolve, reject) => {
      let obj = {};
      if (lat != null && lat != '' && lat != undefined) {
        obj.latitude = lat; // 纬度，非必须
        obj.longitude = lng; // 经度，非必须
      }
      obj.scope = scope;
      obj.onSuccess = function(result) {
        resolve([result.latitude, result.longitude,]);
      };
      obj.onFail = function(err) {
        reject(err);
      };
      sinoware.biz.map.search(obj);
    });
  },
  
  /**
	 * 钉钉免登
	 * @param {*} agentId
	 * @returns
	 */
  ddLogin(agentId) {
    return new Promise((resolve, reject) => {
      if (!agentId) {
        sinoware.device.notification.alert("缺失agentId");
        reject("缺失agentId");
      }
      // agentId:"1174332895",corpId:"dingf5850a5877fdc7d5a39a90f97fcb1e09"
      console.log(agentId, sinoware)
      sinoware.config({
        agentId: agentId,
        jsApiList: ['runtime.info', 'biz.contact.choose', 'runtime.getPasstoken',
          'device.nfc.nfcRead',
          'device.notification.confirm', 'device.notification.alert',
          'device.geolocation.get', 'device.nfc.nfcRead',
          'device.notification.prompt', 'biz.ding.post', 'biz.telephone.call',
          'biz.telephone.showCallMenu',
          'biz.util.openLink', 'biz.navigation', 'biz.util.uploadImage',
          'device.launcher.checkInstalledApps',
          'device.launcher.launchApp', 'biz.map.view', 'biz.map.locate','biz.map.search',
          'biz.util.ut', 'device.base.getUUID',
          'device.geolocation.start', 'device.geolocation.stop',
          'device.audio.onRecordEnd', 'device.audio.startRecord',
          'device.audio.stopRecord', 'device.audio.download', 'device.audio.play',
          'device.audio.pause',
          'device.audio.resume', 'device.audio.stop', 'device.audio.onPlayEnd',
          'biz.chat.openSingleChat','biz.clipboardData.setData',
        ],
      },
      function () {
        sinoware.ready({}, function () {
          sinoware.runtime.permission.requestAuthCode({
            onSuccess: function (token) {
              // 处理页面业务逻辑代码
              sinoware.runtime.getAccountInfo({
                onSuccess: function (data) {
                  console.log('钉钉信息：' + JSON.stringify(data));
                  resolve(data);
                },
                onFail: err => {
                  sinoware.device.notification.alert(
                    'getAccountInfo.fail: ' + JSON
                      .stringify(err));
                  reject(err);
                },
              });
  
            },
            onFail: err => {
              sinoware.device.notification.alert('requestAuthCode.fail:' + JSON
                .stringify(err));
              reject(err);
            },
          });
        })
      });
      console.log(agentId, sinoware)
    });
  },
  /**
   * 测试使用
   * @param {*} agentId 
   * @returns 
   */
  ddDemoLogin(agentId) {
    console.log("鉴权测试");
    return new Promise((resolve, reject) => {
      try {

        sinoware.config({
          agentId: '1289940947', // 必填，微应用ID
          corpId: 'dinga64ba3956ba493ecbc961a6cb783455b',// 必填，企业ID
          timeStamp: '1630582498531', // 必填，生成签名的时间戳
          nonceStr: 'nonceStr', // 必填，自定义固定字符串。
          signature: 'aba3213495e60d5d50bb1f1b5f708430d1018b6e', // 必填，签名
          type: 0,   // 选填。0表示微应用的jsapi,1表示服务窗的jsapi；不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
          jsApiList: [
            'runtime.info', 'biz.contact.choose', 'runtime.getPasstoken', 'device.nfc.nfcRead',
            'device.notification.confirm', 'device.notification.alert', 'device.geolocation.get', 'device.nfc.nfcRead',
            'device.notification.prompt', 'biz.ding.post', 'biz.telephone.call', 'biz.telephone.showCallMenu',
            'biz.util.openLink', 'biz.navigation', 'biz.util.uploadImage', 'device.launcher.checkInstalledApps',
            'device.launcher.launchApp', 'biz.map.view', 'biz.map.locate', 'biz.util.ut', 'device.base.getUUID',
            'device.geolocation.start', 'device.geolocation.stop', 'device.audio.onRecordEnd', 'device.audio.startRecord',
            'device.audio.stopRecord', 'device.audio.download', 'device.audio.play', 'device.audio.pause',
            'device.audio.resume', 'device.audio.stop', 'device.audio.onPlayEnd',
          ], // 必填，需要使用的jsapi列表，注意：不要带dd。
        });

        sinoware.error(function (err) {
          alert('sinoware error: ' + JSON.stringify(err));
        })// 该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题

        sinoware.ready(function () {
          console.log("钉钉ready");
          sinoware.runtime.permission.requestAuthCode({
            corpId: "dinga64ba3956ba493ecbc961a6cb783455b", // 企业id
            onSuccess: function (info) {
              console.log("免登用户授权码", info);
              resolve("wangjian_hz");
            },
          });
        });
      } catch (ddErr) {
        console.error(ddErr);
      }
    });
  },

  /**
	 * 获取设备信息
	 * @returns Promise
	 */
  device() {
    return new Promise((resolve, reject) => {
      let deviceinfo = {
        model: "",
        platform: "DingDing",
        uuid: "",
        version: "",
        manufacturer: "",
        isVirtual: "",
        serial: "",
      };
      sinoware.device.base.getUUID({
        onSuccess: function(data) {
          deviceinfo.uuid = data["uuid"];
          sinoware.device.base.getPhoneInfo({
            onSuccess: function(data) {
              deviceinfo.model = data["model"];
              deviceinfo.version = data["version"];
              deviceinfo.manufacturer = data["brand"];
              deviceinfo.isVirtual = data["operatorType"];
              resolve(deviceinfo);
            },
            onFail: function(err) {
              reject(err);
            },
          });
        },
        onFail: function(err) {
          reject(err);
        },
      });
    });
  },

  /**
  	 * 图片旋转角度
  	 */
  changeImgOrientation(resImg,Orientation){
    return new Promise((resolve, reject) => {
      let self = this;
      let img = new Image();
      img.src = resImg;
      img.onload = function() {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        let imgWidth = canvas.width = this.width;    
        let imgHeight = canvas.height = this.height; 
        // 如果方向角不为1，都需要进行旋转 added by lzk 
        if(Orientation && Orientation != 1){
          switch(Orientation){
          case 6:     // 旋转90度
            canvas.width = this.height;
            canvas.height = this.width;    
            ctx.rotate(Math.PI / 2);
            ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
            break;
          case 3:     // 旋转180度
            ctx.rotate(Math.PI);
            ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
            break;
          case 8:     // 旋转-90度
            canvas.width = imgHeight;
            canvas.height = imgWidth;    
            ctx.rotate(3 * Math.PI / 2);    
            ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
            break;
          }
        }else{
          ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
        }
        let base64code = canvas.toDataURL("image/jpeg");   
        resolve(base64code);
      }
    })
  },
  /**
	 * 从本地相册选择图片或使用相机拍照
	 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
	 * @param {Int} sType 0 默认，1 相册 ， 2 拍照
	 * @param {Number} quality   0-1 
	 * @param {Number} widthScale 0-1 
	 */
  chooseImageToCompress({
    maxSize = 1,
    sType = 0,
    quality = 0.65,
    widthScale = 1,
  }) {
    return new Promise((resolve, reject) => {
      let ar = ['album', 'camera',];
      if (sType == 1) {
        ar = ['album',];
      } else if (sType == 2) {
        ar = ['camera',];
      }
      uni.chooseImage({
        count: maxSize,
        sizeType: ['original', 'compressed',],
        sourceType: ar,
        success: res1 => {
          uni.showLoading({
            title: "正在压缩图片...",
            success() {},
            mask: false,
          });
          Promise.all(res1.tempFilePaths.map(path => {
            return new Promise((resolve, reject) => {
              let self = this;
              let img = new Image();
              let canvas = document.createElement("canvas");
              let ctx = canvas.getContext("2d");
              img.src = path;
              img.onload = function(){
                EXIF.getData(img, function() {
                  let Orientation = EXIF.getTag(this, 'Orientation');
                  let make = EXIF.getTag(this, 'Make');
                  // IOS 13.4以上不需要进行旋转
                  let getVersionRotate = ()  => {
                    let ua = navigator.userAgent.toLowerCase();
                    let ver = ua.match(/cpu iphone os (.*?) like mac os/);
                    try{
                      let b = ver[1].replace(/_/g,".");
                      return self.toNum(b) >= self.toNum(13.4);
                    }catch(err){
                      console.log(err);
                      return false;
                    }
                    
                  };

                  if(Orientation && Orientation != 1 && !getVersionRotate()){
                    // 当旋转值存在且不为1时，调用changeImgOrientation将其还原，并返回base64值
                    self.changeImgOrientation(path,Orientation).then(rxp => {
                      let imgXp = new Image();
                      imgXp.src = rxp;
                      imgXp.onload = function(){
                        canvas.width = imgXp.width;
                        canvas.height = imgXp.height;
                        ctx.drawImage(img, 0, 0, imgXp.width, imgXp.height);
                        let tmp = canvas.toDataURL('image/jpeg');
                        let dp = {
                          graphicContents: tmp.split(',')[1],
                          size:null,
                        };
                        self.getImgByteSize(dp);
                        if(dp.size >= (4 * 1024 * 1024)){ // 大于4M
                          quality = 0.50;
                          widthScale = 0.6;
                        }else if(dp.size >= (3 * 1024 * 1024) && dp.size <= (1024 * 1024 * 4)){ // 大于3M
                          quality = 0.60;
                          widthScale = 0.7;
                        }else if(dp.size >= (1024 * 1024) && dp.size < (1024 * 1024 * 3)){ // 大于1M 小于3M
                          quality = 0.70;
                          widthScale = 0.8;
                        }else{  // 小于1M
                          quality = 0.92;
                          widthScale = 0.9;
                        }
                        if(make != 'Apple'){
                          widthScale = 0.7;
                        }
                        self.compressImage(rxp, path.substring(path.lastIndexOf('.') + 1), maxSize, quality,widthScale, make == 'Apple').then(rpp => {
                          resolve(rpp);
                        });
                      };
                    });
                  }else{
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    let tmp = canvas.toDataURL('image/jpeg');
                    let dp = {
                      graphicContents: tmp.split(',')[1],
                      size:null,
                    };
                    self.getImgByteSize(dp);
                    if(dp.size >= (4 * 1024 * 1024)){ // 大于4M
                      quality = 0.50;
                      widthScale = 0.6;
                    }else if(dp.size >= (3 * 1024 * 1024) && dp.size <= (1024 * 1024 * 4)){ // 大于3M
                      quality = 0.60;
                      widthScale = 0.7;
                    }else if(dp.size >= (1024 * 1024) && dp.size < (1024 * 1024 * 3)){ // 大于1M 小于3M
                      quality = 0.70;
                      widthScale = 0.8;
                    }else{  // 小于1M
                      quality = 0.92;
                      widthScale = 0.9;
                    }
                    if(make != 'Apple'){
                      widthScale = 0.7;
                    }
                    self.compressImage(path, path.substring(path.lastIndexOf('.') + 1), maxSize, quality,widthScale, make == 'Apple').then(rpp => {
                      resolve(rpp);
                    });
                  }
                })
              };
            });
          })).then(resp => {
            uni.hideLoading();
            resolve(resp);
          });
        },
        fail: err => {
          uni.hideLoading();
          reject();
        },
      });
    });
  },
  
  toNum(a) {
    a = a.toString();
    let c = a.split('.');
    let num_place = ["","0","00","000","0000",]; let r = num_place.reverse();
    for (let i = 0;i < c.length;i++){ 
      let len = c[i].length;       
      c[i] = r[len] + c[i];  
    } 
    let res = c.join(''); 
    return res; 
  },
  
  getImgByteSize(data) {
    if (data && data.graphicContents) { // 获取base64图片byte大小
      const equalIndex = data.graphicContents.indexOf('=');  // 获取=号下标
      if (equalIndex > 0) {
        const str = data.graphicContents.substring(0, equalIndex); // 去除=号
        data.size = str.length;
      } else {
        const strLength = data.graphicContents.length;
        data.size = strLength;
      }
    } else {
      data.size = null;
    }
  },
  
  /**
	 * 图片压缩
	 */
  compressImage(file, fileExtra, num, quality = 0.3, widthScale = 0.8, isApple = false) {
    return new Promise((resolve, reject) => {
      let img = new Image();
      img.src = file;
      img.onload = function() {
        let newBase64 = ImageScale.compressImage(img, {
          // 压缩质量
          quality: quality,
          mime: 'image/jpeg',
          // 压缩时的放大系数，默认为1，如果增大，代表图像的尺寸会变大(最大不会超过原图)
          compressScaleRatio:  1,
          // ios的iPhone下主动放大一定系数以解决分辨率过小的模糊问题
          iphoneFixedRatio: 1,
          // 是否采用原图像素（不会改变大小）
          isUseOriginSize: false,
          // 增加最大宽度，增加后最大不会超过这个宽度
          maxWidth: 0,
          // 使用强制的宽度，如果使用，其它宽高比系数都会失效，默认整图使用这个宽度
          forceWidth: img.width * widthScale,
          // 同上，但是一般不建议设置，因为很可能会改变宽高比导致拉升，特殊场景下使用
          forceHeight: 0,
        });
        resolve(newBase64);
      }
    });
  },
	openLink(url) {
		return new Promise((resolve, reject) => {
			 sinoware.biz.util.openLink({
				url: url,
				onSuccess: function(result) {
					resolve(result)
				},
				onFail: function(err) {
					reject(err)
				},
			});
		})
	},
}

export default DingDing;
